<template>
<div>
  <!-- 面包写导航 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片视图 -->
  <el-card>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
      </el-col>
    </el-row>
    <el-table :data="userList" style="width: 100%" border stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column label="状态">
        <template v-slot="slotScpoes">
          <!-- {{ slotScpoes.row }} -->
          <el-switch v-model="slotScpoes.row.mg_state" @change="changeuserstate(slotScpoes.row)"> </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="slotScpoes">
          <el-button type="primary" @click="editHandle(slotScpoes.row.id)" icon="el-icon-edit"></el-button>
          <el-button type="danger" @click="delteUser(slotScpoes.row.id)" icon="el-icon-delete"></el-button>
          <el-tooltip effect="dark" content="分配角色" :enterable="false" placement="top">
            <el-button type="warning" icon="el-icon-setting" @click="fenpeiRoles(slotScpoes.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
  </el-card>
  <!-- 新增dialog -->
  <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="closeDialog">
    <el-form :model="addForm" :rules="addRules" ref="addRef" label-width="75px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="addForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 编辑dialog -->
  <el-dialog title="修改用户" :visible.sync="EditDialogVisible" width="50%" @close="editClosed">
    <el-form ref="editFormRef" :rules="editRules" :model="editForm" label-width="80px">
      <el-form-item label="用户名称">
        <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="EditDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="EditUserHandle">确 定</el-button>
    </span>
  </el-dialog>
  <!-- 分配角色-->
  <el-dialog title="提示" :visible.sync="rolesDialogVisible" width="50%" @close="clearSelect">
    <div>
      <p>当前的用户： {{roleInfo.username}}</p>
      <p>当前的角色： {{roleInfo.role_name}}</p>
      <p>
        分配新角色： <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>
      </p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="rolesDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveRole">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      const reg = /^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/
      if (reg.test(value)) {
        callback()
      }
      return callback(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, callback) => {
      const reg = /^1\d{10}$/
      if (reg.test(value)) {
        callback()
      }
      return callback(new Error('请输入合法的手机号'))
    }
    return {
      editForm: {},
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addRules: {
        username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [{
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [{
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      editRules: {
        email: [{
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [{
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      // 编辑开关
      EditDialogVisible: false,
      // 新增开关
      addDialogVisible: false,
      // 权限开关
      rolesDialogVisible: false,
      roleInfo: {},
      roleList: [],
      selectRoleId: '',
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0
    }
  },
  methods: {
    async changeuserstate(userobj) {
      const {
        data: res
      } = await this.$http.put(`users/${userobj.id}/state/${userobj.mg_state}`)
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('更改用户状态失败')
      }
      this.$message.success('更改用户状态成功')
    },
    handleSizeChange(size) {
      console.log(size)
      this.queryInfo.pagesize = size
      this.getUserList()
    },
    handleCurrentChange(current) {
      console.log(current)
      this.queryInfo.pagenum = current
      this.getUserList()
    },
    async getUserList() {
      // const a = this.$http.get('users', { params: this.queryInfo },function (resolve,reject) {
      //     resolve()
      //  })
      //  console.log(a.then(function(data){
      //         console.log(data);

      //  }));
      const {
        data: res
      } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    closeDialog() {
      this.$refs.addRef.resetFields()
    },
    editClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addRef.validate(async boo => {
        if (!boo) return
        const {
          data: res
        } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) this.$message.error('添加用户失败')
        console.log(res)
        this.$message.success('添加用户成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    async editHandle(id) {
      // console.log(id);
      const {
        data: res
      } = await this.$http.get('users/' + id)
      // console.log(res);
      this.editForm = res.data
      this.EditDialogVisible = true
    },
    EditUserHandle() {
      this.$refs.editFormRef.validate(async boo => {
        if (!boo) return
        const {
          data: res
        } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改信息失败')
        this.$message.success('修改信息成功')
        this.EditDialogVisible = false
        this.getUserList()
      })
    },
    delteUser(id) {
      this.$confirm('此操作将永久删除该用户么?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
          const {
            data: res
          } = await this.$http.delete('users/' + id)
          console.log(res)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配角色
    async fenpeiRoles(roleinfo) {
      this.roleInfo = roleinfo
      // console.log(this.roleInfo)
      const {
        data: res
      } = await this.$http.get('roles')
      this.roleList = res.data
      // console.log(this.roleList)
      this.rolesDialogVisible = true
    },
    async saveRole() {
      const {
        data: res
      } = await this.$http.put(`users/${this.roleInfo.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.status !== 200) return this.$message.error('设置角色失败')
      this.$message.success('设置角色成功！')
      this.rolesDialogVisible = false
      this.getUserList()
    },
    clearSelect () {
      this.roleInfo.id = ''
      this.selectRoleId = ''
    }
  },
  created() {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>
.el-table {
    font-size: 12px;
    margin-top: 10px;
}
.el-pagination {
    margin-top: 10px;
}
</style>
